<template>
  <div class="userRegister">
    <h2>用户注册</h2>
    <a-space direction="vertical" size="large" :style="{ width: '480px' }">
      <a-form
        ref="formRef"
        :rules="rules"
        :model="form"
        @submit="handleSubmit"
        :label-align="'left'"
      >
        <a-form-item
          field="userAccount"
          label="用户账户"
          validate-trigger="blur"
        >
          <a-input v-model="form.userAccount" placeholder="请输入账户" />
        </a-form-item>
        <a-form-item field="userPassword" label="密码" validate-trigger="blur">
          <a-input-password
            v-model="form.userPassword"
            placeholder="请输入密码"
          />
        </a-form-item>
        <a-form-item
          field="checkPassword"
          label="确认密码"
          validate-trigger="blur"
        >
          <a-input-password
            v-model="form.checkPassword"
            placeholder="请输入确认密码"
          />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button html-type="submit">注册</a-button>
            <a-button @click="$refs.formRef.resetFields()">重置</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-space>
  </div>
</template>

<script setup lang="ts">
import { reactive } from "vue";
import { UserControllerService, UserRegisterRequest } from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import { useRouter } from "vue-router";

const router = useRouter();

/**
 * 表单信息
 */
const form = reactive({
  userAccount: "",
  userPassword: "",
  checkPassword: "",
} as UserRegisterRequest);

/**
 * 提交表单
 */
const handleSubmit = async () => {
  const res = await UserControllerService.userRegisterUsingPost(form);
  //注册成功
  if (res.code === 0) {
    message.success("账户注册成功");
    await router.push({
      path: "/user/login",
      replace: true,
    });
  } else {
    message.error("注册失败" + res.message);
  }
};

const rules = {
  userAccount: [
    {
      required: true,
      message: "用户账户未输入",
    },
    {
      validator: (value: any, cb: any) => {
        if (value.length < 4) {
          cb("用户账户过短");
        }
      },
    },
  ],
  userPassword: [
    {
      required: true,
      message: "未输入密码",
    },
    {
      validator: (value: any, cb: any) => {
        if (value.length < 8) {
          cb("密码长度不能小于8");
        }
      },
    },
  ],
  checkPassword: [
    {
      required: true,
      message: "未确认密码",
    },
    {
      validator: (value: any, cb: any) => {
        if (value !== form.userPassword) {
          cb("两次密码不一致");
        }
      },
    },
  ],
};
</script>
